/*
 * Name: EventsData
 * Author: Sam Oakley
 * Date: 25/3/2010
 * Version Number: 1.0
 * Description: Posts key/value pairs to a server
 * Changes History: 
 * 1.0 Created class
 */
package com.blork.rag;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class HTTPPoster { 

    public static HttpResponse doPost(String url, Map<String, String> kvPairs) throws SocketTimeoutException, ClientProtocolException, IOException { 
    	HttpParams httpParameters = new BasicHttpParams();
    	HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
    	HttpConnectionParams.setSoTimeout(httpParameters, 5000);
    	
    	HttpClient httpclient = new DefaultHttpClient(httpParameters); 
        HttpPost httppost = new HttpPost(url); 

         if (kvPairs != null && kvPairs.isEmpty() == false) { 
              List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>( 
                        kvPairs.size()); 
              String k, v; 
              Iterator<String> itKeys = kvPairs.keySet().iterator(); 
              while (itKeys.hasNext()) { 
                   k = itKeys.next(); 
                   v = kvPairs.get(k); 
                   nameValuePairs.add(new BasicNameValuePair(k, v)); 
              } 
              httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
         } 
         HttpResponse response; 
         response = httpclient.execute(httppost); 
         return response; 
    } 
} 
